﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Profile;
using System.Globalization;
using System.IO;
using System.Data;
using GWA.import;
using GWA.GriWebServ;

namespace GWA
{
    public partial class Administrator : System.Web.UI.Page
    {
        int pageSize = 5;
        int totalUsers;
        int totalPages;
        int currentPage = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetUsers();
            }          
        }

        private void GetUsers()
        {

            UserGrid.DataSource = Membership.GetAllUsers(currentPage - 1, pageSize, out totalUsers);
            totalPages = ((totalUsers - 1) / pageSize) + 1;

            // Ensure that we do not navigate past the last page of users.

            if (currentPage > totalPages)
            {
                currentPage = totalPages;
                GetUsers();
                return;
            }

            UserGrid.DataBind();
            CurrentPageLabel.Text = currentPage.ToString();
            TotalPagesLabel.Text = totalPages.ToString();

            if (currentPage == totalPages)
                NextButton.Visible = false;
            else
                NextButton.Visible = true;

            if (currentPage == 1)
                PreviousButton.Visible = false;
            else
                PreviousButton.Visible = true;

            if (totalUsers <= 0)
                NavigationPanel.Visible = false;
            else
                NavigationPanel.Visible = true;
        }

        public void NextButton_OnClick(object sender, EventArgs args)
        {
            currentPage = Convert.ToInt32(CurrentPageLabel.Text);
            currentPage++;
            GetUsers();
        }

        public void PreviousButton_OnClick(object sender, EventArgs args)
        {
            currentPage = Convert.ToInt32(CurrentPageLabel.Text);
            currentPage--;
            GetUsers();
        }


        protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
        {
            TextBox UserName = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
            RadioButtonList Role = (RadioButtonList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("rdbRoles");
            MembershipUser user = Membership.GetUser(UserName.Text);
            Roles.AddUserToRole(user.UserName, Role.SelectedValue);
        }


        protected void btnCont_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("../Admin/Administrator.aspx");
        }

        protected void btnDeleteUsers_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in UserGrid.Rows) 
            { // Access the CheckBox
                CheckBox cb = (CheckBox)row.FindControl("chkDelete");

                if (cb != null && cb.Checked) 
                {
                    Membership.DeleteUser(row.Cells[0].Text);
                } 
            }
            Response.Redirect("../Admin/Administrator.aspx");
        }

        protected void btnImportSubmit_Click(object sender, EventArgs e)
        {
            Label1.Visible = false;
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs(UploadedFilePath);
                DataTable dt = new DataTable();

                if (chkHeaders.Checked)
                {
                    dt = ConvertToDataTable(UploadedFilePath, true);
                    SaveWithHeaders(dt);
                }
                else
                {
                    dt = ConvertToDataTable(UploadedFilePath, false);
                    ChooseHeaders(dt);
                }
                File.Delete(UploadedFilePath);
                btnImportSubmit.Visible = false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)Session["data"];
            Session.Clear();
            dt = SaveColumn(ddlFirstRow.SelectedValue, dt, 0);
            dt = SaveColumn(ddlSecondRow.SelectedValue, dt, 1);
            dt = SaveColumn(ddlThirdRow.SelectedValue, dt, 2);
            dt = SaveColumn(ddlFourthRow.SelectedValue, dt, 3);
            dt = SaveColumn(ddlFifthRow.SelectedValue, dt, 4);
            dt = SaveColumn(ddlSixthRow.SelectedValue, dt, 5);
            dt = SaveColumn(ddlSeventhRow.SelectedValue, dt, 6);
            dt = SaveColumn(ddlEigthRow.SelectedValue, dt, 7);
            dt = SaveColumn(ddlNinthRow.SelectedValue, dt, 8);
            SaveWithHeaders(dt);
        }
        #region Private Methods
        /// <summary>
        /// Converts the uploaded CSV file into a datatable using the CsvImporter class in the Controls directory.
        /// </summary>
        /// <param name="CSVFilePath">The server-side path of the uploaded CSV File</param>
        /// <param name="headers">Does the first row of the CSV File have the column names</param>
        /// <returns></returns>
        private DataTable ConvertToDataTable(string CSVFilePath, bool headers)
        {
            string data = File.ReadAllText(CSVFilePath);
            return CsvParser.Parse(new StringReader(data), headers);
        }
        /// <summary>
        /// Creates the labels from every column in the first row of the DataTable 
        /// </summary>
        /// <param name="dt">DataTable object that was produced from the CSV File</param>
        private void ChooseHeaders(DataTable dt)
        {
            lblFirstRow.Text = dt.Rows[0][0].ToString();
            lblSecondRow.Text = dt.Rows[0][1].ToString();
            lblThirdRow.Text = dt.Rows[0][2].ToString();
            lblFourthRow.Text = dt.Rows[0][3].ToString();
            lblFifthRow.Text = dt.Rows[0][4].ToString();
            lblSixthRow.Text = dt.Rows[0][5].ToString();
            lblSeventhRow.Text = dt.Rows[0][6].ToString();
            lblEigthRow.Text = dt.Rows[0][7].ToString();
            lblNinthRow.Text = dt.Rows[0][8].ToString();
            Session.Add("data", dt);
            Panel2.Visible = true;
        }
        /// <summary>
        /// Calls the web service and saves the datatable into the database
        /// </summary>
        /// <param name="dt">DataTable object that was produced from the CSV File</param>
        private void SaveWithHeaders(DataTable dt)
        {
            dt.TableName = "Importees";
            Service1 s1 = new Service1();
            int success = s1.ImportPatient(dt);
            Label1.Text = "Successfully imported " + success.ToString() + " out of " + dt.Rows.Count.ToString() + " records!";
            Panel1.Visible = true;
            Panel2.Visible = false;
            btnImportSubmit.Visible = true;
        }
        /// <summary>
        /// Getter method returning the server-side path of the uploaded file.
        /// </summary>
        private string UploadedFilePath
        {
            get { return Server.MapPath(Path.Combine("~/tmp/", FileUpload1.FileName)); }
        }
        /// <summary>
        /// Saves the Column header information if there was none in the original CSV File.
        /// </summary>
        /// <param name="selValue">Selected Value from a dropdownlist</param>
        /// <param name="dt">Datatable Session Object</param>
        /// <param name="ColNumber">The column number that is being saved</param>
        /// <returns></returns>
        private DataTable SaveColumn(string selValue, DataTable dt, int ColNumber)
        {
            switch (selValue)
            {
                case "FirstName":
                    dt.Columns[ColNumber].ColumnName = "FirstName";
                    return dt;
                case "LastName":
                    dt.Columns[ColNumber].ColumnName = "LastName";
                    return dt;
                case "Address":
                    dt.Columns[ColNumber].ColumnName = "Address";
                    return dt;
                case "City":
                    dt.Columns[ColNumber].ColumnName = "City";
                    return dt;
                case "State":
                    dt.Columns[ColNumber].ColumnName = "State";
                    return dt;
                case "Zip":
                    dt.Columns[ColNumber].ColumnName = "Zip";
                    return dt;
                case "Healthcare":
                    dt.Columns[ColNumber].ColumnName = "Healthcare";
                    return dt;
                case "Diagnosis":
                    dt.Columns[ColNumber].ColumnName = "Diagnosis";
                    return dt;
                case "Phone":
                    dt.Columns[ColNumber].ColumnName = "Phone";
                    return dt;
            }

            return null;
        }
        #endregion

    }
}
